﻿package hibernate.xml44.test;

import hibernate.xml44.pojo.WebUser;
import hibernate.xml44.util.HibernateHandler;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
public class Hql {
	public static void main(String[] args) {
//		queryHql();
//		getAndLoadHql();
//		deleteHql();
//		updateHql();
	}

	public static void updateHql() {
		/*update*/
		Session session = HibernateHandler.getCurrentSession();
		session.beginTransaction();
		WebUser webUser = (WebUser) session.load(WebUser.class,110);
		webUser.setName("dong");
		session.update(webUser);
		session.getTransaction().commit();
	}

	public static void deleteHql() {
		/*delete*/
		Session session = HibernateHandler.getCurrentSession();
		session.beginTransaction();
		WebUser webUser = (WebUser) session.load(WebUser.class,110);
		session.delete(webUser);
		session.getTransaction().commit();
	}

	public static void getAndLoadHql() {
		/*load & get*/
		Session session = HibernateHandler.getCurrentSession();
		session.beginTransaction();
		WebUser webUser = (WebUser)session.get(WebUser.class,110);
		System.out.println(webUser.getName());
		webUser = (WebUser)session.load(WebUser.class,110);
		System.out.println(webUser.getName());
		session.getTransaction().commit();
	}

	@SuppressWarnings("unchecked")
	public static void queryHql() {
		/*Query 接口*/
		Session session = HibernateHandler.getCurrentSession();
		session.beginTransaction();
		/*问号方式*/
		String hql = "from WebUser where id=?";
		/*参数方式*/
//		String hql = "from WebUser where id=:id";
		Query query = session.createQuery(hql);
		//参数方式设值
//		query.setParameter("id",110);
		//问号方式设置,注意是从0开始
		query.setInteger(0, 110);
		List<WebUser> list = query.list();
		for(WebUser wu:list){
			System.out.println(wu.getName());
		}
		/*确定返回一个对象就用uniqueResult()*/
		WebUser webUser = (WebUser) session.createQuery("from WebUser where id=110").uniqueResult();
		System.out.println(webUser.getName());
		session.getTransaction().commit();
	}
}


